package com.computergames.server.domain;

import lombok.Data;

@Data
public class GobangBorad {
    private static final int SIZE = 15; // 棋盘大小为15x15
    private final int[][] board = new int[SIZE][SIZE];

    // 字母坐标到索引的映射方法
    private int letterToIndex(String letter) {
        if (letter == null || letter.length() != 1 || !Character.isUpperCase(letter.charAt(0))) {
            throw new IllegalArgumentException("Invalid coordinate letter");
        }
        return letter.charAt(0) - 'A';
    }

    // 玩家代号映射
    private int playerCode(String player) {
        if ("hei".equals(player)) {
            return 1; // 黑棋
        } else if ("bai".equals(player)) {
            return 2; // 白棋
        } else {
            throw new IllegalArgumentException("Invalid player code");
        }
    }

    // 更新棋盘状态，"hei"代表黑棋，"bai"代表白棋
    public boolean updateBoard(String xStr, int y, String player) {
        int x = letterToIndex(xStr);
        int playerValue = playerCode(player);

        if (x < 0 || x >= SIZE || y < 0 || y >= SIZE) {
            return false; // 棋子位置超出棋盘范围，更新失败
        }

        if (board[x][y] != 0) return false; // 位置已有棋子，更新失败
        board[x][y] = playerValue;

        return true;
    }

    // 检查胜利条件
    public boolean checkWinCondition(String xStr, int y, String player) {
        int x = letterToIndex(xStr);
        int playerValue = playerCode(player);
        // 检查横向
        int count = 1; // 已有一个棋子在当前位置
        for (int j = 1; j <= 4; j++) {
            if (y + j < SIZE && board[x][y + j] == playerValue) count++;
            else break;
        }
        for (int j = 1; j <= 4; j++) {
            if (y - j >= 0 && board[x][y - j] == playerValue) count++;
            else break;
        }
        if (count >= 5) return true;

        // 检查纵向
        count = 1;
        for (int i = 1; i <= 4; i++) {
            if (x + i < SIZE && board[x + i][y] == playerValue) count++;
            else break;
        }
        for (int i = 1; i <= 4; i++) {
            if (x - i >= 0 && board[x - i][y] == playerValue) count++;
            else break;
        }
        if (count >= 5) return true;

        // 检查两个对角线
        count = 1;
        for (int k = 1; k <= 4; k++) {
            if (x + k < SIZE && y + k < SIZE && board[x + k][y + k] == playerValue) count++;
            else break;
        }
        for (int k = 1; k <= 4; k++) {
            if (x - k >= 0 && y - k >= 0 && board[x - k][y - k] == playerValue) count++;
            else break;
        }
        if (count >= 5) return true;

        count = 1;
        for (int k = 1; k <= 4; k++) {
            if (x + k < SIZE && y - k >= 0 && board[x + k][y - k] == playerValue) count++;
            else break;
        }
        for (int k = 1; k <= 4; k++) {
            if (x - k >= 0 && y + k < SIZE && board[x - k][y + k] == playerValue) count++;
            else break;
        }
        return count >= 5;
    }
}
